<template>
  <div
    class="plan-edit-box"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="pageLoading"
  >
    <div class="plan-page-header">
      <div class="header-title">{{ title }}</div>
      <div class="header-btns">
        <RPButton optType="reset" style="margin-right: 10px" @click="hideFun" text="取消" />
        <RPButton v-if="!disabledPage" optType="create" type="info" @click="save" text="确认" />
      </div>
    </div>
    <div class="plan-page-content">
      <Form
        :model="modelForm"
        :disabled="disabledPage"
        ref="editForm"
        class="ivu-form-no-margin-bottom"
        :rules="rule"
        :label-width="150"
      >
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="ruleName" label="规则名称：">
              <Input v-model="modelForm.ruleName" :maxlength="50" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item prop="reportType" label="报表类型：">
              <Select  v-model="modelForm.reportType">
                <Option
                  v-for="item in reportTypeList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.text }}</Option
                >
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item prop="reportName" label="报表名称：">
              <Select  v-model="modelForm.reportName" @on-change="reportNameChange">
                <Option
                  v-for="item in reportNameList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.text }}</Option
                >
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="triggerCondition" label="触发条件：">
              <Select  v-model="modelForm.triggerCondition">
                <Option
                  v-for="item in triggerConditionList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.text }}</Option
                >
              </Select>
            </Form-item>
          </Col>
        </Row>
        <!-- <Row v-if="modelForm.reportType" :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="triggerCondition" :label="yearOrQuarterLable">
              <Select  v-model="modelForm.triggerCondition">
                <Option
                  v-for="item in triggerConditionList"
                  :value="item.value"
                  :key="item.value"
                  >{{ item.text }}</Option
                >
              </Select>
            </Form-item>
          </Col>
        </Row> -->
        <Row v-if="showYearOrQuarter" :gutter="20" class="code-row-bg">
          <Col span="24" style="border:none;">
          <div class="Selecequarters" >
            <Form-item prop="reportYear" :label="yearOrQuarterLable">
              <DatePicker type="year" v-model="modelForm.reportYear" :options="optionss"  placeholder="请选择年份" style="width: 200px" />
            </Form-item>
            <span v-if="modelForm.reportName == '数字化转型专项实施方案任务表'" style="margin:10px; margin-left: -590px;margin-right:-130px">-</span>
            <Form-item v-if="modelForm.reportName == '数字化转型专项实施方案任务表'" prop="reportQuarter">
              <Select   v-model="modelForm.reportQuarter" style="width: 24%;" placeholder="请选择季度">
                <Option  v-for="item in datasList" :key="item.key" :value="item.value">{{item.value}}</Option>
              </Select>
            </Form-item >
          </div>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="triggerTime" label="触发时间：">
              <DatePicker
                v-model="triggerTime"
                type="datetime"
                :editable="false"
                placeholder="请选择触发时间"
                style="width: 200px"
                @on-change="changeTriggerTime"
              />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="receiveWay" label="接收方式：">
              <CheckboxGroup v-model="receiveWayArr"  @on-change="changeReceiveWay">
                <Checkbox
                  v-for="item in receiveWayList"
                  :label="item.value"
                  :key="item.value"
                >{{ item.text }}</Checkbox>
              </CheckboxGroup>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item :required="true" label="接收人：">
              <RadioGroup v-model="modelForm.receiveType"  @on-change="receiveTypeChange">
                <Radio
                  v-for="item in receiveTypeList"
                  :label="item.value"
                  :key="item.value"
                >{{ item.text }}</Radio>
              </RadioGroup>
            </Form-item>
          </Col>
        </Row>
        <div class="addresee">
            <Row :gutter="20" class="code-row-bg">
            <Col span="24" style="border: none">
                <Form-item prop="receivers">
                  <div class="user-list">
                      <div class="user" v-for="(item, index) in receiverList" :key="index">
                        <span class="user-name">{{item.name}}</span>
                        <Icon v-show="!disabledPage" type="ios-close" @click="removeUser(item)"/>
                      </div>
                  </div>
                  <Input v-show="false" v-model="modelForm.receivers" type="textarea" :rows="4" placeholder="请输入" />
                </Form-item>
            </Col>
            </Row>
            <RPButton v-if="action != 'detail'" class="button" optType="create" text="选择" @click="selectAddress"></RPButton>
        </div>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="mailTitle" label="邮件主题：">
              <Input v-model="modelForm.mailTitle" :maxlength="50" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="24" style="border: none">
            <Form-item prop="context" label="邮件内容：">
              <Input v-model="modelForm.context" :maxlength="2000" type="textarea" :rows="4" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
      </Form>
    </div>
  </div>
</template>
<script>
import ruleConfigApi from '@/api/ruleConfig.js'
import SeleceAddressDatas from '../SeleceAddressDatas.vue'
import selectGroup from '../selectGroup.vue'
import { 
  TRIGGER_CONDITION_LIST,
  TRIGGER_CONDITION_NOT_SUBMIT,
  TRIGGER_CONDITION_NOT_DELAY,
  RECEIVE_WAY_LIST,
  REMIND_WAY_EMAIL,
  RECEIVE_TYPE_LIST,
  RECEIVE_TYPE_PERSON,
} from '../const.js'
export default {
  components: {},
  name: 'createConfig',
  props: {
    disabledPage: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default() {
        return ''
      }
    },
    id: {
        type: String,
        default: ''
    },
    action: {
        type: String,
        default: 'create'
    },
  },
  data() {
    const validatorRuleName =  (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入规则名称'))
      }else {
        callback()
      }
      //  else if (!/^([\u4e00-\u9fa5A-Za-z]){2,64}$/.test(value)) {
      //   callback(new Error('规则名称仅支持中文、英文，2-64个字符'))
      // } 
    }
    const validatormailTitle =  (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮件主题'))
      }else {
        callback()
      }
      //  else if (!/^([\u4e00-\u9fa5A-Za-z]){2,64}$/.test(value)) {
      //   callback(new Error('规则名称仅支持中文、英文，2-64个字符'))
      // } 
    }
    const validatorTriggerTime =  (rule, value, callback) => {
      if (this.disabledPage) {
        callback()
      } else {
        if (!value) {
          callback(new Error('请选择触发时间'))
        } else if (Date.now() > new Date(value).valueOf()) {
          callback(new Error('触发时间必须选择未来的时间'))
        } else {
          callback()
        }
      }
    }
    const validatorTriggerCondition = (rule, value, callback) => {
      if (!value && value !== TRIGGER_CONDITION_NOT_SUBMIT) {
        callback(new Error('请选择触发条件'))
      } else {
        callback()
      }
    }
    const validatorReportYear = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择年度'))
      } else {
        callback()
      }
    }
    const validatorReportQuarter = (rule, value, callback) => {
      if (!value && this.modelForm.reportName == '数字化转型专项实施方案任务表') {
        callback(new Error('请选择季度'))
      } else {
        callback()
      }
    }
    const validatorReceiveWay = (rule, value, callback) => {
      if (!value && value !== `${REMIND_WAY_EMAIL}`) {
        callback(new Error('请选择接收方式'))
      } else {
        callback()
      }
    }
    
    return {
      datasList:[
          {key:'0',value:'1'},
          {key:'1',value:'2'},
          {key:'2',value:'3'},
          {key:'3',value:'4'},
      ],
      optionss:{
        disabledDate(date){
          // const disabledDate = date.getFullYear()
          // return ( disabledDate > 2025 || disabledDate < 2021 )
          // 先不做控制
          return false
        }
      },
      pageLoading: false,
      reportTypeList: [
        {text: '专项工作', value: '专项工作'},
      ],
      allReportNameList: {
        '专项工作': [
          // {text: '关键业务环节数字化覆盖度', value: '关键业务环节数字化覆盖度'},
          {text: '数字化转型专项实施方案任务表', value: '数字化转型专项实施方案任务表'}
        ]
      },
      reportNameList: [],
      triggerConditionList: [],
      receiveWayList: RECEIVE_WAY_LIST,
      receiveWayArr: [REMIND_WAY_EMAIL],
      receiveTypeList: RECEIVE_TYPE_LIST,
      triggerTime: '',
      receiverList: [],
      modelForm: {
        id: '',
        ruleName: '',
        reportType: '',
        reportName: '',
        triggerCondition: '', // 0-未提交, 1-未更新
        reportYear: '',
        reportQuarter: '',
        triggerTime: '',
        receiveWay: `${REMIND_WAY_EMAIL}`, // 0-邮件, 1-润工作, 多选以逗号分割
        receiveType: RECEIVE_TYPE_PERSON, // 0-收件人, 1-收件人组
        receivers: '',
        mailTitle: '',
        context: ''
      },
      rule: {
        ruleName: [{ required: false, validator: validatorRuleName.bind(this), trigger: 'blur' }],
        reportType: [{ required: true, message: '请选择报表类型', trigger: 'blur' }],
        reportName: [{ required: true, message: '请选择报表名称', trigger: 'blur' }],
        triggerCondition: [{ required: false, validator: validatorTriggerCondition.bind(this), trigger: 'change' }],
        reportYear: [{ required: true, validator: validatorReportYear.bind(this), trigger: 'change' }],
        reportQuarter: [{ required: true, validator: validatorReportQuarter.bind(this), trigger: "change" }],
        triggerTime: [{ required: false, validator: validatorTriggerTime.bind(this), trigger: 'change' }],
        receiveWay: [{ required: false, validator: validatorReceiveWay.bind(this), trigger: 'change' }],
        receivers: [{ required: true, message: '请选择接收人', trigger: 'blur' }],
        mailTitle: [{ required: false, validator: validatormailTitle.bind(this), trigger: 'blur' }],
        context: [{ required: true, message: '请输入邮件内容', trigger: 'blur' }]
      },
      triggerTimeOption:{
        disabledDate(date){
          return date && (date.valueOf() + 24 * 60 * 60 * 1000) < Date.now()
        }
      }
    }
  },
  computed: {
    yearOrQuarterLable() {
      return this.modelForm.reportName == '关键业务环节数字化覆盖度' ? '年度：' : '季度：'
    },
    showYearOrQuarter() {
      return this.modelForm.reportName && this.modelForm.triggerCondition != TRIGGER_CONDITION_NOT_DELAY
    },
  },
  created() {
    this.getDetail()
  },
  watch: {
    'modelForm.reportType': {
      handler(val) {
        if (val) {
          this.reportNameList = this.allReportNameList[val]
        }
      }
    },
    'modelForm.reportName': {
      handler(val) {
        // this.$set(this.modelForm, 'triggerCondition', '')
        // this.$set(this.modelForm, 'context', '')
        this.setTriggerConditionList()
      }
    },
    'modelForm.triggerCondition': {
      handler(val) {
        this.setTriggerConditionList()
        this.setRemindContext()
      }
    }
  },
  beforeMount: function () {},
  mounted() {},
  beforeDestroy: function () {},
  destroyed: function () {},
  methods: {
    reportNameChange() {
      this.$set(this.modelForm, 'triggerCondition', '')
      this.$set(this.modelForm, 'context', '')
    },
    setTriggerConditionList() {
      let reportName = this.modelForm.reportName
      if (reportName == '数字化转型专项实施方案任务表') {
        this.triggerConditionList = TRIGGER_CONDITION_LIST
      } else if (reportName == '关键业务环节数字化覆盖度') {
        this.triggerConditionList = TRIGGER_CONDITION_LIST.filter(item => item.value == TRIGGER_CONDITION_NOT_SUBMIT)
      }
    },
    setRemindContext() {
      let triggerCondition = this.modelForm.triggerCondition
      let reportName = this.modelForm.reportName
      if (reportName == '数字化转型专项实施方案任务表') {
        if (triggerCondition === TRIGGER_CONDITION_NOT_DELAY) {
          this.$set(this.modelForm, 'context', '{BU}，截止至{time}系统检测到贵单位提交的{report name}中有已延期任务项，请关注！')
        } else if (triggerCondition === TRIGGER_CONDITION_NOT_SUBMIT) {
          this.$set(this.modelForm, 'context', '{BU}，截止至{time}系统检测到贵单位仍未提交/更新{filling time}季度{report name}，请及时处理！')
        }
      } else if (reportName == '关键业务环节数字化覆盖度') {
        if (triggerCondition === TRIGGER_CONDITION_NOT_SUBMIT) {
          this.$set(this.modelForm, 'context', '{username}您好，截止至{time}系统检测到您仍未提交{filling time}年度{report name}，请及时提交！')
        }
      } else {
        this.$set(this.modelForm, 'context', '')
      }
    },
    removeUser(item) {
      this.receiverList = this.receiverList.filter((user) => user.id !== item.id)
      let idList = this.receiverList.map(item => item.id)
      this.modelForm.receivers = idList.length ? idList.join(',') : ''
    },
    receiveTypeChange() {
      this.modelForm.receivers = ''
      this.receiverList = []
    },
    hideFun() {
      this.$parent.hide()
    },
    getDetail() {
        if (this.id) {
            ruleConfigApi.getDetail({id: this.id}).then(res => {
                if (res.data.code == 200) {
                    let result = res.data.data
                    let temp = {}
                    Object.keys(this.modelForm).forEach(key => {
                        temp[key] = result[key]
                    })
                    temp.reportTime = result.reportTime
                    temp.reportYear = temp.reportTime ? new Date(temp.reportTime).Format('yyyy') : ''
                    temp.reportQuarter = ''
                    if (temp.reportName == '数字化转型专项实施方案任务表' && temp.reportTime && temp.reportTime.split('-')[1]) {
                      temp.reportQuarter = temp.reportTime.split('-')[1]
                    }
                    delete temp.reportTime
                    this.modelForm = temp
                    if (result.itsReceiverGroupVoList) {
                      this.receiverList = result.itsReceiverGroupVoList.map(item => {
                        return {
                          name: item.groupName,
                          id: item.id
                        }
                      })
                    } else {
                      this.receiverList = result.receivers.split(',').map(item => {
                        return {
                          name: item,
                          id: item
                        }
                      })
                    }
                    
                    this.receiveWayArr = (''+this.modelForm.receiveWay).split(',')
                    this.triggerTime = this.modelForm.triggerTime
                }
            })
        }
    },
    selectAddress() {
       new this.$pageModal(
        this.modelForm.receiveType == RECEIVE_TYPE_PERSON ? SeleceAddressDatas : selectGroup,
          {
          props: {
              /* menuId: menu.id */
              title: this.modelForm.receiveType == RECEIVE_TYPE_PERSON ? "选择收件人" : "选择收件人组",
          }
          },
          (data) => {
            if (data && data.length) {
              if (this.modelForm.receiveType == RECEIVE_TYPE_PERSON) {
                data.forEach(item => {
                  if (!this.receiverList.find(user => user.id == item)) {
                    this.receiverList.push({
                      name: item,
                      id: item
                    })
                  }
                })
              } else {
                data.forEach(item => {
                  if (!this.receiverList.find(user => user.id == item.id)) {
                    this.receiverList.push({
                      id: item.id,
                      name: item.groupName
                    })
                  }
                })
              }
              let nameList = this.receiverList.map(item => item.id)
              this.modelForm.receivers = nameList.length ? nameList.join(',') : ''
            }
          }
      )
    },
    changeTriggerTime(data) {
      this.modelForm.triggerTime = data
    },
    changeReceiveWay(data) {
      this.$set(this.modelForm, 'receiveWay', data.join(','))
    },
    init() {},
    save() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = {...this.modelForm}
          if (params.triggerCondition != TRIGGER_CONDITION_NOT_DELAY) {
            params.reportTime = new Date(params.reportYear).Format('yyyy')
            if (params.reportName == '数字化转型专项实施方案任务表') {
              params.reportTime = params.reportTime + '-' + params.reportQuarter
            }
            delete params.reportYear
            delete params.reportQuarter
          }
          params.receiveWay = this.receiveWayArr.join(',')
          if (this.action == 'edit') {
            ruleConfigApi.editInfo(params).then(res => {
              if (res.data.code == 200) {
                this.$Message.success({
                  content: '操作成功',
                  duration: 3
                })
                this.$emit('Close', true)
              }
            })
          } else {
            ruleConfigApi.createInfo(params).then(res => {
              if (res.data.code == 200) {
                this.$Message.success({
                  content: '操作成功',
                  duration: 3
                })
                this.$emit('Close', true)
              }
            })
          }
        } else {
          this.$Message.error({
            content: '请完善表单信息',
            duration: 3
          })
          return 0
        }
      })
    }
  },
  directives: {}
}
</script>

<style lang="less" scoped>
/deep/.ivu-btn-warning {
  padding: 4px 23px;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
  border-radius: 0;
}
.Selecequarters {
  display:flex;
  /deep/.ivu-form-item-content{
      margin-left: -446px;
  }
  /deep/.ivu-form-item-content{
        margin-left: 2px;
        width: 800px;
  }
}
.plan-edit-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .plan-page-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    align-items: center;
    padding: 0 20px;
    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .plan-page-content {
    flex: 1;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 0 20%;
  }
}
.addresee {
  position: relative;
  .button {
    position: absolute;
    right: -100px;
    top: 0;
  }
}
.user-list {
  width: 100%;
  min-height: 32px;
  border: 1px solid #d8d8d8;
  padding: 2px 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .user{
    height: 26px;
    line-height: 26px;
    background: #f5f5f5;
    padding: 0 10px;
    border-radius: 5px;
    margin: 3px 5px;
    .user-name {
      margin-right: 4px;
    }
    .ivu-icon-ios-close {
      font-size: 18px;
      cursor: pointer;
    }
  }
}
</style>
